package org.bigpigman.el.test;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description 二维码生成工具
 * @Author 朱咸军
 * @Date 2019/6/14
 **/
public class QRCodeUtil {

    private static final int BLACK = 0xFF000000;
    private static final int WHITE = 0xFFFFFFFF;

    public static void main(String[] args) throws IOException, WriterException {
        QRCodeUtil.createQRcode("DDDDDDDDDDDDDDDDD", "D:\\ddd.jpg", 300);
    }

    public static void createQRcode(String url,String imageUrl, int width) throws WriterException, IOException {
        String content = url ;
        MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
        Map hints = new HashMap();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, width, width, hints);
    }

    /**
     * 获取生成二维码时的BufferedImage
     * @return
     */
    public static BufferedImage getBufferedImageWith(String url, int width) throws WriterException {
        MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
        Map hints = new HashMap();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        BitMatrix matrix = multiFormatWriter.encode(url, BarcodeFormat.QR_CODE, width, width, hints);
        int matrixWidth = matrix.getWidth();
        int matrixHeight = matrix.getHeight();
        BufferedImage image = new BufferedImage(matrixWidth, matrixHeight, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < matrixWidth; x++) {
            for (int y = 0; y < matrixHeight; y++) {
                image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
            }
        }
        return image;
    }
}
